package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @desc 处理图形报表
 * @Date 2020/10/21 11:13
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    //注入会员的接口
    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    /**
     * 会员数量折线图
     *
     * @return
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {

        //返回的数据是一个map集合
        Map<String, Object> map = new HashMap<>();
        //存放所有的月份
        List<String> months = new ArrayList<>();

        //获取过去的12个月
        Calendar calendar = Calendar.getInstance();   //获取日历的对象，获取的就是当前的时间
        //通过月份，获取前面的12个月的时间
        calendar.add(Calendar.MONTH, -12);
        //遍历获取前面12个月的月份，添加到集合里面
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(date));
        }
        //将所有的月份添加到map里
        map.put("months", months);


        //查询的每个月拥有的会员的数量,存到集合里面
        List<Integer> memberCount = memberService.findMemberCountByMonths(months);

        //将所有的月份的数据添加到map里
        map.put("memberCount", memberCount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);

    }


    /**
     * 会员预约套餐的百分比(饼形图)
     *
     * @return
     */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {

        try {
            //返回数据封装到集合中
            Map<String, Object> data = new HashMap<>();

            //存放套餐的名称
            List<String> setmealNames = new ArrayList();
            //每种套餐预约的数量
            List<Map<String, Object>> setmealCount = setmealService.findSetmealCount();
            data.put("setmealCount", setmealCount);

            //遍历查询到的所有的数据
            for (Map<String, Object> map : setmealCount) {
                //拿出所有的套餐的名称
                String name = (String) map.get("name");
                //将所有的套餐名称放到套餐的名称的几个里面
                setmealNames.add(name);
            }

            //将数据添加到map里面，返回给页面
            data.put("setmealNames", setmealNames);

            //返回数据
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, data);


        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);

        }
    }

    /**
     * 查询统计的数据
     *
     * @return
     */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {

        try {
            Map<String, Object> data = reportService.getBusinessReportData();

            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 下载excel报表文件
     *
     * @return
     */
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {

        try {
            Map<String, Object> data = reportService.getBusinessReportData();

            //获取文件的磁盘绝对路径    File.separator 表示 文件夹的分割父   linux 是 /  windows是 \\ 这个可以根据系统动态获取
            String path = request.getSession().getServletContext().getRealPath("template")
                    + File.separator + "report_template.xlsx";


            //获取文件模板（工作蒲）
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(path)));
            //获取工作表  第一张表
            XSSFSheet sheet = workbook.getSheetAt(0);

            //获取到报表的详细数据
            //今天的时间
            String reportDate = (String) data.get("reportDate");
            sheet.getRow(2).createCell(5).setCellValue(reportDate); //设置值

            //今天新增会员数
            Integer todayNewMember = (Integer) data.get("todayNewMember");
            sheet.getRow(4).createCell(5).setCellValue(todayNewMember);

            //今天总会员数
            Integer totalMember = (Integer) data.get("totalMember");
            sheet.getRow(4).createCell(7).setCellValue(totalMember);

            //本周新增会员数
            Integer thisWeekNewMember = (Integer) data.get("thisWeekNewMember");
            sheet.getRow(5).createCell(5).setCellValue(thisWeekNewMember);

            //本月新增会员数
            Integer thisMonthNewMember = (Integer) data.get("thisMonthNewMember");
            sheet.getRow(5).createCell(7).setCellValue(thisMonthNewMember);

            //今日预约数
            Integer todayOrderNumber = (Integer) data.get("todayOrderNumber");
            sheet.getRow(7).createCell(5).setCellValue(todayOrderNumber);

            //今日到诊数
            Integer todayVisitsNumber = (Integer) data.get("todayVisitsNumber");
            sheet.getRow(7).createCell(7).setCellValue(todayVisitsNumber);

            //本周预约数
            Integer thisWeekOrderNumber = (Integer) data.get("thisWeekOrderNumber");
            sheet.getRow(8).createCell(5).setCellValue(thisWeekOrderNumber);

            //本周到诊数
            Integer thisWeekVisitsNumber = (Integer) data.get("thisWeekVisitsNumber");
            sheet.getRow(8).createCell(7).setCellValue(thisWeekVisitsNumber);

            //本月预约数
            Integer thisMonthOrderNumber = (Integer) data.get("thisMonthOrderNumber");
            sheet.getRow(9).createCell(5).setCellValue(thisMonthOrderNumber);

            //本月到诊数
            Integer thisMonthVisitsNumber = (Integer) data.get("thisMonthVisitsNumber");
            sheet.getRow(9).createCell(7).setCellValue(thisMonthVisitsNumber);

            //热门套餐
            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) data.get("hotSetmeal");

            //定义第一个套餐的行数
            int rowNum = 12;
            for (Map<String, Object> map : hotSetmeal) {
                //获取map里面的数据
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                String proportion = (String) map.get("proportion");
                //获取行
                sheet.getRow(rowNum).createCell(4).setCellValue(name);
                sheet.getRow(rowNum).createCell(5).setCellValue(setmeal_count);
                sheet.getRow(rowNum).createCell(6).setCellValue(proportion);
                rowNum++; //自增
            }


            //通过流，将数据响应给客户端
            ServletOutputStream outputStream = response.getOutputStream();

            //通过响应头告诉浏览器下载的内容格式
            //表示下载的是 微软的 excel 格式
            response.setContentType("application/vnd.ms-excel");
            //以附件格式下载，下载名为 report.xlsx
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");


            //通过流，将文件写到流里面
            workbook.write(outputStream);


            //关流，刷新
            outputStream.flush();
            outputStream.close();
            workbook.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }


    /**
     * pdf报表
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response) {
        try {
            //通过server获取数据(直接填充的数据)
            Map<String, Object> data = reportService.getBusinessReportData();

            //热门套餐的数据(需要遍历的数据)
            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) data.get("hotSetmeal");


            //获取模板的路径    File.separator 表示 文件夹的分割父   linux 是 /  windows是 \\ 这个可以根据系统动态获取
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template")
                    + File.separator + "health_business3.jrxml";

            //编译成jasper后的路径
            String jasperPath = request.getSession().getServletContext().getRealPath("template")
                    + File.separator + "health_business3.jasper";

            //编译模板     参数一 模板路径   参数2 编译后的位置
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);


            //填充数据    参数1 jasper的二进制文件  参数2 需要向模板添加的数据（基本的数据）  参数3 通过javabean将将集合放进去（遍历的数据）
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, data, new JRBeanCollectionDataSource(hotSetmeal));


            //通过流，将数据响应给客户端
            ServletOutputStream outputStream = response.getOutputStream();

            //通过响应头告诉浏览器下载的内容格式
            //表示下载的是 pdf 格式
            response.setContentType("application/pdf");
            //以附件格式下载，下载名为 report.jasper
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");

            //输出文件 通过流进行传输
            JasperExportManager.exportReportToPdfStream(jasperPrint,outputStream);

            //关流，刷新
            outputStream.flush();
            outputStream.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}

